package com.qxzn.module.im.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.greendao.bean.ChatMsgBean;
import com.qxzn.app.bean.MsgBean;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.DateUtil;
import com.qxzn.app.util.SystemUtil;
import com.qxzn.module.im.R;
import com.qxzn.module.im.R2;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/5/20.
 */
public class MsgListAdapter extends RecyclerView.Adapter<MsgListAdapter.ViewHolder> {

    private Context context;
    private List<ChatMsgBean> dataList;
    private ChatMsgBean item;

    private int lastPlayPosition;
    private ImageView lastPlayView;
    private boolean isPlay;
    private MediaPlayer mediaPlay;
    private View.OnClickListener sendFailClick;
    private View.OnClickListener llContentClick;
    private View.OnClickListener llContentClick1 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag(R.id.indexTag);
//            ChatMsgBean bean = dataList.get(position);
            MsgListAdapter.ViewHolder holder = (MsgListAdapter.ViewHolder) v.getTag(R.id.viewHolder);
            AppUtil.showLog("位置：" + position);
            if (llContentClick != null) {
                llContentClick.onClick(v);
            }
            if (lastPlayPosition == position && isPlay) {
                isPlay = false;
                SystemUtil.stopMedia(mediaPlay);
                notifyItemChanged(lastPlayPosition);
//                resetLastAnim();
            } else {
                isPlay = false;
                notifyItemChanged(lastPlayPosition);
                SystemUtil.stopMedia(mediaPlay);
//                resetLastAnim();
                playAudio(holder, position);
                AnimationDrawable currentAnim = (AnimationDrawable) holder.ivIconVoice.getBackground();
                currentAnim.start();
            }
            lastPlayPosition = position;
        }
    };

    public MsgListAdapter(Context context, List<ChatMsgBean> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = new View(context);
        switch (viewType) {
            case MsgBean.VOICE_SEND:
                view = LayoutInflater.from(context).inflate(R.layout.item_chat_voice_send, parent, false);
                break;
            case MsgBean.VOICE_RECEIVE:
                view = LayoutInflater.from(context).inflate(R.layout.item_chat_voice_receive, parent, false);
                break;
        }
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        item = dataList.get(position);
        if (item.getDirect() == 1){//接收
            if (item.getUnread() == 1) {//已读
                holder.viewUnread.setVisibility(View.GONE);
            } else {
                holder.viewUnread.setVisibility(View.VISIBLE);
            }
            holder.pgbSendStatus.setVisibility(View.GONE);
        } else {
            holder.viewUnread.setVisibility(View.GONE);
            if (item.getSendStatus() == 0) {
                holder.pgbSendStatus.setVisibility(View.VISIBLE);
                holder.pgbSendStatus.setTag(position);
                holder.pgbSendStatus.setOnClickListener(sendFailClick);
                holder.ivSendFail.setVisibility(View.GONE);
            } else {
                holder.pgbSendStatus.setVisibility(View.GONE);
                if (item.getSendStatus() == 1) {
                    holder.ivSendFail.setVisibility(View.GONE);
                } else {
                    holder.ivSendFail.setVisibility(View.VISIBLE);
                    holder.ivSendFail.setTag(position);
                    holder.ivSendFail.setOnClickListener(sendFailClick);
                }
            }
        }
        holder.tvLength.setText(Math.round(item.getFileDuration()) + "\"");
        if (position == 0) {
            holder.tvTime.setVisibility(View.VISIBLE);
            holder.tvTime.setText(DateUtil.formMillisToStr(item.getCreateTime(), DateUtil.yearToSecPattern1));
        } else {
            if (item.getCreateTime() - dataList.get(position - 1).getCreateTime() > 2 * 60 * 1000) {
                holder.tvTime.setVisibility(View.VISIBLE);
                holder.tvTime.setText(DateUtil.formMillisToStr(item.getCreateTime(), DateUtil.yearToSecPattern1));
            } else {
                holder.tvTime.setVisibility(View.GONE);
            }
        }
        holder.llContent.setTag(R.id.indexTag, position);
        holder.llContent.setTag(R.id.viewHolder, holder);
        holder.llContent.setOnClickListener(llContentClick1);

        AnimationDrawable currentAnim = (AnimationDrawable) holder.ivIconVoice.getBackground();
        if (lastPlayPosition == position && isPlay) {
            currentAnim.start();
            AppUtil.showLog("播放：" + position);
        } else {
            currentAnim.stop();
            currentAnim.selectDrawable(0);
//            AppUtil.showLog("停止：" + position);
        }
        AppUtil.showLog("-------");
    }

    /**
     * 播放当前点击的音频
     *  @param holder
     * @param position
     */
    private void playAudio(final ViewHolder holder, final int position) {
        AppUtil.showLog("位置1：" + position);//"/storage/emulated/0/Android/data/com.qxzn.desktopxiaopairobot/files/audio/sss.amr"
        mediaPlay = SystemUtil.playMedia(!TextUtils.isEmpty(dataList.get(position).getFilePath()) ? dataList.get(position).getFilePath() : HttpRequest.BASE_URL + dataList.get(position).getFileUrl(), new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                isPlay = true;
                notifyItemChanged(position);
//                playAnim(holder, position);
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                AppUtil.showShortToast(context, "播放错误");
                isPlay = false;
                notifyItemChanged(position);
//                stopAnim(holder, position);
                return false;
            }
        }, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                isPlay = false;
                notifyItemChanged(position);
//                stopAnim(holder, position);
            }
        });
    }

    /**
     * 重置上一个动画
     */
    private void resetLastAnim() {
        if (lastPlayView != null) {
            AnimationDrawable currentAnim = (AnimationDrawable) lastPlayView.getBackground();
            if (currentAnim != null) {
                currentAnim.stop();
                currentAnim.selectDrawable(0);
            }
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        item = dataList.get(position);
        if (item.getMsgType() == 2) {
            if (item.getDirect() == 0) {
                return MsgBean.VOICE_SEND;
            } else {
                return MsgBean.VOICE_RECEIVE;
            }
        }
        return item.getMsgType();
    }

    private void playAnim(ViewHolder holder, int position) {
        if (lastPlayPosition == position) {
            AnimationDrawable currentAnim = (AnimationDrawable) holder.ivIconVoice.getBackground();
            if (!currentAnim.isRunning()) {
                isPlay = true;
                currentAnim.start();
                AppUtil.showLog("开启当前动画1：" + holder.tvTime.getText() + "，" + DateUtil.formMillisToStr(dataList.get(position).getCreateTime(), DateUtil.yearToSecPattern1));
            } else {
                isPlay = false;
                currentAnim.stop();
                currentAnim.selectDrawable(0);
                AppUtil.showLog("关闭当前动画1：" + holder.tvTime.getText() + "，" + DateUtil.formMillisToStr(dataList.get(position).getCreateTime(), DateUtil.yearToSecPattern1));
            }
        } else {
            if (lastPlayView != null) {
                AnimationDrawable lastAnim = (AnimationDrawable) lastPlayView.getBackground();
                if (lastAnim != null) {
                    lastAnim.stop();
                    lastAnim.selectDrawable(0);
                    AppUtil.showLog("关闭上一个动画：" + holder.tvTime.getText() + "，" + DateUtil.formMillisToStr(dataList.get(position).getCreateTime(), DateUtil.yearToSecPattern1));
                }
            }
            AnimationDrawable currentAnim = (AnimationDrawable) holder.ivIconVoice.getBackground();
            currentAnim.start();
            AppUtil.showLog("开启当前动画2：" + holder.tvTime.getText() + "，" + DateUtil.formMillisToStr(dataList.get(position).getCreateTime(), DateUtil.yearToSecPattern1));
        }
        lastPlayPosition = position;
        lastPlayView = holder.ivIconVoice;
    }

    private void stopAnim(ViewHolder iv_icon_voice, int position) {
        AnimationDrawable currentAnim = (AnimationDrawable) iv_icon_voice.ivIconVoice.getBackground();
        currentAnim.stop();
        currentAnim.selectDrawable(0);
    }

    public void setSendFailClick(View.OnClickListener sendFailClick) {
        this.sendFailClick = sendFailClick;
    }

    public void setLlContentClick(View.OnClickListener llContentClick) {
        this.llContentClick = llContentClick;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R2.id.tv_time)
        TextView tvTime;
        @BindView(R2.id.iv_head)
        ImageView ivHead;
        @BindView(R2.id.view_unread)
        View viewUnread;
        @BindView(R2.id.tv_length)
        TextView tvLength;
        @BindView(R2.id.iv_icon_voice)
        ImageView ivIconVoice;
        @BindView(R2.id.pgb_send_status)
        ProgressBar pgbSendStatus;
        @BindView(R2.id.iv_send_fail)
        ImageView ivSendFail;
        @BindView(R2.id.ll_content)
        LinearLayout llContent;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

}
